package ch04;

import java.util.LinkedList;
import java.util.Queue;

//BFS
public class BreadthFirstPaths {
    private boolean[] marked;
    private final int s;
    private int pathTo[];

    public BreadthFirstPaths(Graph graph, int s) {
        this.s = s;
        this.marked = new boolean[graph.V()];
        pathTo = new int[graph.V()];
        BFS(graph, s);

    }

    public static void main(String[] args) {
        Graph graph = Graph.getGraphUseCase();
        BreadthFirstPaths bfp = new BreadthFirstPaths(graph, 2);
        bfp.BFS(graph, 4);
        bfp.printPath(4);

    }

    public boolean marked(int v) {
        return marked[v];
    }
    private void printPath(int v){
        if(pathTo[v] == 0) {
            System.out.print(v + " --> ");
            return;
        }
        else printPath(pathTo[v]);
        System.out.print(v + " --> ");
    }

    private void BFS(Graph graph, int s) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(s);
        while (!queue.isEmpty()) {
            Integer v = queue.poll();
            marked[v] = true;

            for (Integer t : graph.adj(v)) {
                if (!marked[t]) {
                    queue.offer(t);
                    //
                    pathTo[t] = v;
                }
            }
        }
    }
}
